<?php

namespace App\Service;

require_once 'AipImageClassify.php';

use Illuminate\Support\Facades\Cache;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;

class CommonService
{
    /**
     * @param Request $request
     * @return mixed
     * User: 张浩
     * Date: 2022/11/25
     * Time: 10:54
     * 内容审核
     */
    public static function contentAudit($content)
    {

        //ApiKey和SecretKey从自己在百度智能云上创建的应用信息里获取
        $token = self::getAccessToken(config('baidu.apikey'), config('baidu.secretkey'));

        $url = config('baidu.texturl') . $token;

        $bodys = array(
            'text' => $content
        );

        $res = self::curlPost($url, $bodys);

        //结果转成数组
        $res = json_decode($res, true);

        //根据自己的业务逻辑进行处理

        return $res;
    }

    /**
     * @param $image
     * @return mixed
     * User: 张浩
     * Date: 2022/11/25
     * Time: 10:54
     * 图片审核
     */
    public static function imageAudit($image)
    {

        $fileTmp = $image->getPathname();
        $token = self::getAccessToken('ApiKey ', 'SecretKey ');
        $url = config('baidu.imgurl') . $token;
        $img = file_get_contents($fileTmp);//本地路径
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img
        );
        $res = self::curlPost($url, $bodys);
        //结果转成数组
        $res = json_decode($res, true);
        //根据自己的业务逻辑进行处理
        return $res;
    }

    /**
     * @param string $url
     * @param string $param
     * @return bool|string
     * User: 张浩
     * Date: 2022/11/25
     * Time: 11:08
     * CURL的Post请求方法
     */
    function curlPost($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }

    /**
     * @param string $ApiKey
     * @param string $SecretKey
     * @param string $grantType
     * @return mixed
     * User: 张浩
     * Date: 2022/11/25
     * Time: 11:08
     * 获取百度开放平台的票据
     * 参考链接：https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
     */
    public static function getAccessToken($ApiKey = '', $SecretKey = '', $grantType = 'client_credentials')
    {

        $url = config('baidu.piaourl');
        $post_data['grant_type'] = $grantType;
        $post_data['client_id'] = $ApiKey;
        $post_data['client_secret'] = $SecretKey;
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);

        $res = self::curlPost($url, $post_data);
        //进行把返回结果转成数组
        $res = json_decode($res, true);
        if (isset($res['error'])) {
            exit('API Key或者Secret Key不正确');
        }
        $accessToken = $res['access_token'];
        return $accessToken;
    }

    /**
     * @param null $token
     * @return int|mixed
     * User: 张浩
     * Date: 2022/11/11
     * Time: 19:33
     * 验证token
     */
    public static function verifyToken($token = null)
    {
        //检测是否接收到了token
        if (empty($token)) {
            return 0;
        }
        //转化为可以验证的token
        $token = (new Parser())->parse((string)$token);
        //验证基本设置
        $data = new ValidationData();
        $data->setIssuer('teacher');
        $data->setAudience('student');
        $data->setId('MarsLei');

        if (!$token->validate($data)) {
            return 0;
        }
        //验证签名
        $signer = new Sha256();
        if (!$token->verify($signer, 'my')) {
            return 0;
        }
        //验证通过，返回用户id
        return $token->getClaim('uid');
    }

    /**
     * @param null $uid
     * @return string
     * User: 张浩
     * Date: 2022/11/11
     * Time: 19:32
     * 生成token
     */
    public static function createToken($uid = null)
    {
        $signer = new Sha256();//加密规则
        $time = time();//当前时间

        $token = (new Builder())
            ->issuedBy('teacher')//签发人
            ->canOnlyBeUsedBy('student')//接收人
            ->identifiedBy('MarsLei', true) //标题id
            ->issuedAt($time)//发出令牌的时间
            ->canOnlyBeUsedAfter($time) //生效时间(即时生效)
            ->expiresAt($time + 3600) //过期时间
            ->with('uid', $uid) //用户id
            ->sign($signer, 'my') //签名
            ->getToken(); //得到token
        return (string)$token;
    }

    /**
     * @param $url
     * @return mixed
     * User: 张浩
     * Date: 2022/11/10
     * Time: 19:42
     * 封装curl请求第三方接口
     * get方式
     */
    public static function geturl($url)
    {
        $headerArray = array("Content-type:application/json;", "Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }
    public static function curlGetCommunity($latitude,$longitude)//根据经纬度获取其社区
    {
        $url = "http://api.map.baidu.com/geocoder?location={$latitude},{$longitude}";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
        $communityArr = json_decode(json_encode(simplexml_load_string($output)), true);
        $communityName = $communityArr['result']['addressComponent']['district'];
        return $communityName;
    }

    /**
     * @param $data
     * @param int $pid
     * @param int $level
     * @param string $html
     * @return array
     * User: 张浩
     * Date: 2022/11/10
     * Time: 19:42
     * 页面层级样式
     */
    public static function getTree($data, $pid = 0, $level = 0, $html = '--')
    {
        //最终权限数组
        static $result = []; //1,2,3,4
        //处理数组为空，直接返回result
        if (empty($data)) {
            return $result;
        }
        foreach ($data as $item) {
            if ($item['p_id'] == $pid) {
                $item['html'] = str_repeat($html, $level);  // -- ---- ---------
                $item['level'] = $level + 1;

                $result[] = $item;//1，2，3，4，5，6
                self::getTree($data, $item['id'], $item['level']);
            }
        }
        return $result;
    }

    /**
     * @param array $data
     * @param int $pid
     * @return array
     * User: 张浩
     * Date: 2022/11/10
     * Time: 19:42
     * 无限级递归处理数据
     */
    public static function infiniteSort(array $data, $pid = 0)
    {
        // 返回的结果
        $arr = [];
        foreach ($data as $val) {
            // 给定的PID是当前记录的上级ID
            if ($pid == $val['p_id']) {
                // 递归
                $val['sub'] = self::infiniteSort($data, $val['id']);
                $arr[] = $val;
            }
        }
        return $arr;
    }

    /**
     * @param $request
     * @param $filename
     * @return array
     * User: 张浩
     * Date: 2022/11/10
     * Time: 19:41
     * 七牛云上传
     */
    public static function qiniu($request, $filename)
    {
        //获取图片信息
        $file = $request->file($filename)->store('', 'qiniu');
        //拼接上传信息
        $pic = config('qiniu.url') . $file;
        //返回信息
        return self::success(200, '上传成功', $pic);
    }

    /**
     * @param $phone
     * @return array
     * User: 张浩
     * Date: 2022/11/10
     * Time: 19:41
     * 接口限制
     */
    public static function requestThrottle($phone)
    {
        $nums = Cache::get($phone . 'num');
        if ($nums == 1) return self::fail(9999, '稍后再试', $nums);
        $num = Cache::get($phone . 'code');
        if ($num != null) {
            if ($num < 3) {
                Cache::put($phone . 'num', 1, 10);
                Cache::put($phone . 'code', 0, 10);
                return self::fail(9999, '请求次数过多', $num);
            } else {
                Cache::put($phone . 'code', $num + 1, 10);
            }
        } else {
            Cache::put($phone . 'code', 1, 10);
        }
    }

    /**
     * @param $tel
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * User: 张浩
     * Date: 2022/10/24
     * Time: 20:39
     * 短信宝发送短信
     */
    public static function sendSms($tel)
    {
        $statusStr = array(
            "0" => "短信发送成功",
            "-1" => "参数不全",
            "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
            "30" => "密码错误",
            "40" => "账号不存在",
            "41" => "余额不足",
            "42" => "帐户已过期",
            "43" => "IP地址限制",
            "50" => "内容含有敏感词"
        );
        $code = config('telnote.code');
        $smsapi = config('telnote.url');
        $user = config('telnote.user'); //短信平台帐号
        $pass = config('telnote.password'); //短信平台密码
        $content = '您的手机验证码为：' . $code;//要发送的短信内容
        $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $tel . "&c=" . urlencode($content);
        $result = self::geturl($sendurl);
        if ($result == 0) {
            Cache::put('shq' . $tel, $code, 5 * 60);
            return self::success(200, $statusStr[$result], $code);
        }
        return self::fail(9999, $statusStr[$result], []);
    }

    /**
     * @param $phone
     * @return array|string|string[]
     * User: 张浩
     * Date: 2022/11/10
     * Time: 19:41
     * 手机号隐藏中间4位
     */
    public static function telHidden($phone)
    {
        $phone = substr_replace($phone, '****', 3, 4);
        return $phone;
    }

    /**
     * @param $idcard
     * @return array|string|string[]
     * User: 张浩
     * Date: 2022/11/10
     * Time: 19:41
     * 身份证号隐藏
     */
    public static function userCardHidden($idcard)
    {
        $idcard = substr_replace($idcard, '***********', 3, 11);
        return $idcard;
    }

    /**
     * @param $phone
     * @return array|int
     * User: 张浩
     * Date: 2022/11/10`
     * Time: 19:41
     * 手机号验证
     */
    public static function phoneCheck($phone)
    {
        //判断传来的参数是否为空
        if (empty($phone)) return self::fail(9999, '手机号不能为空', []);
        //正则验证手机号格式是否正确
        $user = preg_match('/^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/', $phone);
        //手机号不正确是返回
        if ($user == 0) return self::fail(9999, '手机格式不正确', []);
        return 1;
    }

    /**
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return array
     * User: 张浩
     * Date: 2022/11/10
     * Time: 19:41
     * 成功回调
     */
    public static function success($code = 200, $msg = '成功', $data = [])
    {
        return [
            'code' => $code,
            'data' => $data,
            'msg' => $msg
        ];
    }

    /**
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return array
     * User: 张浩
     * Date: 2022/11/10
     * Time: 19:41
     * 失败回调
     */
    public static function fail($code = 9999, $msg = '失败', $data = [])
    {
        return [
            'code' => $code,
            'data' => $data,
            'msg' => $msg
        ];
    }
}
